package com.pactera.madp.cp.controller.oms.contact;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.log.annotation.SysLog;
import com.pactera.madp.common.security.annotation.Inner;
import com.pactera.madp.cp.api.constant.DeptConstants;
import com.pactera.madp.cp.api.dto.contact.ContactDetailsTendencyDTO;
import com.pactera.madp.cp.api.entity.CorpEntity;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.contact.ContactPageVO;
import com.pactera.madp.cp.api.vo.contact.ContactStaticsDetailsVO;
import com.pactera.madp.cp.api.vo.contact.ContactStaticsTendencyVO;
import com.pactera.madp.cp.api.vo.contact.ContactStatisticsDataVO;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.service.ICorpService;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkDeptService;
import com.pactera.madp.cp.service.WorkContactEmployeeStaticsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ContactEmployeeStaticsController
 *
 * @author jun
 * @version 1.0
 * 2021/7/20 9:22
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/statics")
@Api(value = "statics", tags = "客户统计")
public class ContactEmployeeStaticsController {

    private final WorkContactEmployeeStaticsService workContactEmployeeStaticsService;
    private final ICorpService corpService;
    /**
     * 远程调用部门信息
     */
    private final RemoteDeptService remoteDeptService;
    private final IWorkDeptService workDeptService;
    private final IWorkContactService workContactService;

    @Inner
    @SysLog("同步客户信息")
    @PutMapping("/syn")
    @ApiOperation(value = "同步客户信息")
    public void synchronizationContact(){
        List<CorpEntity> corpEntities = corpService.list(Wrappers.<CorpEntity>lambdaQuery());
        for (CorpEntity entity : corpEntities) {
            workContactEmployeeStaticsService.synchronizationContact(entity.getCorpId());
        }
    }

    @GetMapping("/details")
    @ApiOperation(value = "客户统计基本信息")
    public R<ContactStaticsDetailsVO> getContactDetails(){
        return R.ok(workContactEmployeeStaticsService.getContactDetails());
    }

    @GetMapping("/tendency")
    @ApiOperation(value = "华融湘江客户统计趋势图")
    public R<List<ContactStaticsTendencyVO>> getContactDetailsTendency(ContactDetailsTendencyDTO dto){
        Integer type = dto.getType();
        switch (type) {
            case 1:
                return R.ok(workContactEmployeeStaticsService.getContactTotalCount(dto));
            case 2:
                return R.ok(workContactEmployeeStaticsService.getWxContactCount(dto));
            case 3:
                return R.ok(workContactEmployeeStaticsService.getQywxContactCount(dto));
            case 4:
                return R.ok(workContactEmployeeStaticsService.getCrmContactCount(dto));
            case 5:
                return R.ok(workContactEmployeeStaticsService.getNonBankContactCount(dto));
            case 6:
                return R.ok(workContactEmployeeStaticsService.getLossContactCount(dto));
        }
        return R.failed("查询字段类型不在1-6内");
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public R<Page<ContactStaticsDetailsVO>> getPageList(ContactDetailsTendencyDTO dto, Page page){
        return R.ok(workContactEmployeeStaticsService.getPageList(dto, page));
    }

    @SysLog("客户统计导出Excel")
    @PostMapping("/excel")
    @ApiOperation(value = "客户统计导出Excel")
    public void exitExcel(@RequestBody ContactDetailsTendencyDTO dto, HttpServletResponse response, OutputStream out){
        workContactEmployeeStaticsService.exitExcel(dto, response, out);
    }

    @GetMapping("/getStaticsData/{deptId}")
    @ApiOperation(value = "华融湘江客户统计基础信息")
    public R<ContactStatisticsDataVO> getStatisticsData(@PathVariable("deptId")Integer deptId) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        ContactStatisticsDataVO entity = workContactEmployeeStaticsService.getStatisticsDatas(deptId, wxDeptId);
        return R.ok(entity);
    }

    @GetMapping("/getStaticsDataPage/{deptId}")
    @ApiOperation(value = "华融湘江客户统计分页查询")
    public R getStatisticsDataPage(@PathVariable("deptId")Integer deptId,
                                   @RequestParam(value = "contactName",required = false) String contactName,
                                   @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                   @RequestParam(value = "EmployeeName",required = false) String EmployeeName,
                                   Page page) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .select(WorkDeptEntity::getLevel,WorkDeptEntity::getId)
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        Integer level = workDeptEntity.getLevel();
        if (level < DeptConstants.SUB_BRANCH_LEVEL) {
            LinkedHashMap pageResult = (LinkedHashMap) remoteDeptService.getChildrenPage(deptId, page).getData();
            Page<ContactStatisticsDataVO> contactStatisticsDataVOs = JSON.parseObject(JSON.toJSONString(pageResult), new TypeReference<Page<ContactStatisticsDataVO>>() {});
            contactStatisticsDataVOs.getRecords().forEach(c -> {
                ContactStatisticsDataVO entity1 = workContactEmployeeStaticsService.getStatisticsDatas(c.getId(), Integer.parseInt(c.getCode()));
                c.setContactTotalCount(entity1.getContactTotalCount());
                c.setWxContactCount(entity1.getWxContactCount());
                c.setQywxContactCount(entity1.getQywxContactCount());
                c.setCrmContactCount(entity1.getCrmContactCount());
                c.setNonBankContactCount(entity1.getNonBankContactCount());
                c.setLossContactCount(entity1.getLossContactCount());
                c.setYesterdayAddedCount(entity1.getYesterdayAddedCount());
                c.setCode(c.getName());
                c.setName(entity1.getName());
            });
            return R.ok(contactStatisticsDataVOs);
        } else {
            List<ContactPageVO> vos = new ArrayList<>();
            vos = workContactService.getWorkContactsByDeptId(workDeptEntity.getId());
            vos.forEach(v -> {
                v.setMobile(JSONArray.parseArray(v.getMobile()).isEmpty() ? "" : JSONArray.parseArray(v.getMobile()).get(0).toString());
                switch (v.getType()) {
                    case 1:
                        v.setTypeText("微信用户");
                        break;
                    case 2:
                        v.setTypeText("企业微信用户");
                        break;
                    default:
                        v.setTypeText("");
                }
                switch (v.getGender()) {
                    case 0:
                        v.setGenderText("未知");
                        break;
                    case 1:
                        v.setGenderText("男");
                        break;
                    case 2:
                        v.setGenderText("女");
                    default:
                        v.setGenderText("");
                }
            });
            if (contactName == null || contactName.equals("")) {
            } else {
                vos = vos.stream().filter(contactPageVO -> contactPageVO.getName().contains(contactName)).collect(Collectors.toList());
            }
            if (phoneNum == null || phoneNum.equals("")) {
            } else {
                vos = vos.stream().filter(contactPageVO -> contactPageVO.getMobile().contains(phoneNum)).collect(Collectors.toList());
            }
            if (EmployeeName == null || EmployeeName.equals("")) {
            } else {
                vos = vos.stream().filter(contactPageVO -> contactPageVO.getEmployeeName().contains(EmployeeName)).collect(Collectors.toList());
            }
            Page<ContactPageVO> split = PageUtil.split(vos, (int) page.getCurrent(), (int) page.getSize());
            return R.ok(split);
        }
    }

}
